 /*****************************
 * Copyright (c) 2008 by Jielee Co. Ltd.  All rights reserved.
 ****************************/
package com.core.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/** 
 * @{#} MD5.java Create on Sep 5, 2008 4:54:43 PM 
 * <p>
 *  MD5 加密.
 * </p>
 * @author <a href="mailto:rainasmoon@126.com">wanghui</a>   
 * @version v 0.1
 */
public class MD5 {
	
	public static final int OXFF = 0xff;
	public static final int OX10 = 0x10;
	
	/**
	 * 
	 */
	private MD5() {
		
	}
	
    /**
     * Encodes a string.
     *
     * @param str String to encode
     * @return Encoded String
     * @throws NoSuchAlgorithmException java.security.NoSuchAlgorithmException
     */
    public static String crypt(String str) throws NoSuchAlgorithmException {
        if (str == null || str.length() == 0) {
            throw new IllegalArgumentException("String to encript cannot be null or zero length");
        }

        StringBuffer hexString = new StringBuffer();

        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(str.getBytes());
        byte[] hash = md.digest();

        for (byte aHash : hash) {
            if ((OXFF & aHash) < OX10) {
                hexString.append("0").append(Integer.toHexString((OXFF & aHash)));
            } else {
                hexString.append(Integer.toHexString(OXFF & aHash));
            }
        }

        return hexString.toString();
    }
}
